package com.antdant.service;

import com.antdant.entity.Prize;
import com.antdant.repository.PrizeRepository;
import com.antdant.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;

/**
 * @Author Lee Yunc
 * @Date 2021/3/15 11:23
 * @Description:
 * @Version 1.0
 */
@Slf4j
@Service
public class PrizeService {

    @Resource
    private PrizeRepository prizeRepository;

    /**
     * 分页查询奖品信息
     *
     * @param current
     * @param size
     * @param prizeName
     * @return
     */
    public Page<Prize> getAllPrizes(Integer current, Integer size, String prizeName) {
        Pageable pageable = PageRequest.of(current - 1, size);

        return prizeRepository.findAll((Specification<Prize>) (root, criteriaQuery, criteriaBuilder) -> {
            log.info("奖品按名字查找：" + prizeName);
            Predicate temp = criteriaBuilder.like(root.get("prizeName"), "%" + prizeName + "%");
            return temp;
        }, pageable);
    }

    /**
     * 增加新奖品
     *
     * @param prize
     * @return
     */
    public Prize addNewPrize(Prize prize) {
        Prize newPrize = createNewPrize();
        newPrize.setDescription(prize.getDescription());
        newPrize.setImage(prize.getImage());
        newPrize.setPrizeName(prize.getPrizeName());
        return prizeRepository.saveAndFlush(newPrize);
    }

    //新奖品初始化
    private Prize createNewPrize() {
        Prize prize = new Prize();
        prize.setCreateTime(DateUtils.getNowTime());
        return prize;
    }

    /**
     * 根据id删除奖品
     *
     * @param prizeId
     * @return
     */
    public Boolean deletePrize(Integer prizeId) {
        try {
            prizeRepository.deleteById(prizeId);
            return true;
        } catch (RuntimeException e) {
            return false;
        }
    }
}
